<script setup lang="ts">
import { getCurrentInstance, ref, onMounted, onUpdated, nextTick } from 'vue'
import { onBeforeRouteLeave } from 'vue-router'
import MeScroll from 'mescroll.js'
import 'mescroll.js/mescroll.min.css'
const { proxy } = getCurrentInstance()

/* ---- */
const userInfo = proxy.$Store.get('userInfo') || {}
const logUser = proxy.$Store.get('logUser') || {}
const WXConfig = proxy.$Store.get('WXConfig') || {}

/* --设置微信分享功能-- */
proxy.$WxTool.loadJsdk(WXConfig, (obj) => {
  if (!obj) return
  // ----
  obj.hideMenuItem()
})

/* ---- */
// --mescroll--
const noData = proxy.$Global.noData
let mescroll = null
const items = ref([])

/* ---- */
const layer = ref()
const layerBox = ref()

/* ---- */
// --getData--
const startMeScroll = () => {
  mescroll = new MeScroll(proxy.$refs.dataScroll, {
    up: {
      callback: getListData,
      isBounce: false,
      page: { num: 0, size: 15 },
      htmlNodata: '<p class="upwarp-nodata">-- 到底啦 --</p>',
      noMoreSize: 5,
      toTop: {
        src: '/pics/mescroll-totop.png',
        offset: 1000
      },
      empty: {
        warpId: proxy.$refs.dataList,
        tip: noData
      }
    }
  })
}
const getListData = (page) => {
  getListDataFromNet({
    forUrl: 'contract/index',
    forData: {
      params: {
        'ContractSearch[dealer_id]': logUser.id,
        // ----
        sort: 'SORT_DESC',
        // ----
        page: page.num,
        PageSize: page.size
      }
    }
  }, page.num, page.size, (curPageData) => {
    setListData(curPageData).then((result) => {
      mescroll.endSuccess(curPageData ? curPageData.length : 0, true)
      items.value = items.value.concat(result)
    })
  }, (resMsg) => {
    mescroll.endErr()
    proxy.$Myfun.forToast(layer.value, 'open', resMsg)
  })
}
const getListDataFromNet = (option, pageNum, pageSize, successCallback, errorCallback) => {
  if (Number(pageNum) === 1) {
    if (document.querySelector('.upwarp-nodata')) { document.querySelector('.upwarp-nodata').style.visibility = 'hidden' }
    items.value = []
  }
  // ----
  proxy.$http.get(option.forUrl, option.forData).then((res) => {
    successCallback && successCallback(res.items)
  }).catch((err) => { errorCallback && errorCallback(err) })
}
const setListData = async (items) => {
  const newItems = []
  for (let i = 0; i < Number(items.length); i++) {
    const item = items[i]
    // ----
    let forStatus = {}
    proxy.$Myfun.getJsonData(item.status_arr, (resJson) => {
      if (Number(resJson.length) > 0) forStatus = resJson[0]
    })
    // ----
    let forSignImg = ''
    proxy.$Myfun.getJsonData(item.cg_sign, (resJson) => {
      if (Number(resJson.length) > 0) forSignImg = resJson[0].image
    })
    // ----
    newItems.push({
      id: item.id,
      name: proxy.$Myfun.setText(item.name),
      date: proxy.$Myfun.getDateShort(item.make_date),
      // ----
      status: forStatus,
      // ----
      isSign: Number(item.is_sign) === 1,
      signImg: forSignImg,
      // --复制新建专用--
      gh_name: item.gh_name,
      gh_leader: item.gh_leader,
      gh_telphone: item.gh_telphone,
      gh_wlleader: item.gh_wlleader,
      gh_wltelphone: item.gh_wltelphone,
      gh_address: item.gh_address,
      // ----
      cg_name: item.name,
      cg_leader: item.cg_leader,
      cg_telphone: item.cg_telphone,
      sh_leader: item.sh_leader,
      sh_telphone: item.sh_telphone,
      sh_address: item.sh_address,
      // ----
      pro_arr: item.pro_arr,
      total_amount: item.total_amount,
      terms: item.terms
    })
  }
  return newItems
}
const divScroll = (event) => { proxy.$Myfun.setImgToTop() }
// ----
const getAuditFun = (type, item, key) => {
  switch (Number(type)) {
    case 1: {
      proxy.$Myfun.openPage(proxy, 'push', 'ForContract')
      break
    }
    case 2: {
      const forItem = item || {}
      proxy.$Myfun.openPage(proxy, 'push', 'ContractListAdm', { id: forItem.id })
      break
    }
    case 3: {
      proxy.$Myfun.openPage(proxy, 'push', 'ContractShare', { id: item.id, dealer_id: logUser.id })
      break
    }
    case 4: {
      item.status[key] = Number(item.status[key]) === 1 ? 0 : 1
      const forStatusArr = JSON.stringify(item.status)
      // ----
      proxy.$http.patch('contract/update?id=' + item.id, {
        status_arr: forStatusArr,
        // ----
        config_id: userInfo.config_id,
        openid: userInfo.openid
      }).then((res) => {}).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
      break
    }
    case 5: {
      const options = {
        content: '是否复制新增合同',
        button: [{
          text: proxy.$Global.layer.btnCancel
        }, {
          text: '复制新增',
          class: 'xw-color-24',
          callback: () => {
            layerBox.value.close()
            // ----
            proxy.$http.post('contract/create', {
              dealer_id: logUser.id,
              // ----
              gh_name: item.gh_name,
              gh_leader: item.gh_leader,
              gh_telphone: item.gh_telphone,
              gh_wlleader: item.gh_wlleader,
              gh_wltelphone: item.gh_wltelphone,
              gh_address: item.gh_address,
              // ----
              name: item.cg_name,
              cg_leader: item.cg_leader,
              cg_telphone: item.cg_telphone,
              sh_leader: item.sh_leader,
              sh_telphone: item.sh_telphone,
              sh_address: item.sh_address,
              // ----
              pro_arr: item.pro_arr,
              total_amount: item.total_amount,
              terms: item.terms,
              // ----
              config_id: userInfo.config_id,
              openid: userInfo.openid
            }).then((res) => {
              if (res) {
                mescroll.scrollTo(0)
                mescroll.resetUpScroll()
              }
            }).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
          }
        }]
      }
      proxy.$Myfun.isIndepth(layerBox.value, 'open', options)
      break
    }
  }
}

/* ---- */
onMounted(() => {
  // --创建MeScroll对象--
  setTimeout(() => { startMeScroll() }, 500)
})
onUpdated(() => { nextTick(() => { proxy.$Myfun.setSectionH() }) })
onBeforeRouteLeave(() => { if (mescroll) mescroll.destroy() })
</script>

<template>
  <div>
    <header class="xw-bg-gray">
      <div class="forTop xw-flex xw-flex-align">
        <div class="TOP-title xw-flex-W1">合同列表</div>
        <span class="TOP-submit xw-WBlue xw-radius-3" @click="getAuditFun(1)">默认设置</span>
        <span class="TOP-submit xw-WBlue xw-radius-3 TOP-Lfg" @click="getAuditFun(2)">制作合同</span>
      </div>
    </header>
    <div class="xw-section">
      <div ref="dataScroll" class="mescroll" @scroll="divScroll">
        <ul class="list-tract xw-flex xw-flex-column" ref="dataList">
          <li class="xw-bg-white xw-Tfg" v-for="(item, index) in items">
            <div class="LTT-title xw-act" :class="{'xw-color-24': item.isSign || Number(item.signImg.length) > 0}" @click="getAuditFun(3, item)">{{item.name}}</div>
            <div class="LTT-btns xw-flex xw-flex-align xw-flex-justify">
              <div class="xw-btn" :class="[Number(item.status.sent) === 1 ? 'xw-WBlueB' : 'xw-GBlue']" @click="getAuditFun(4, item, 'sent')">已发送</div>
              <div class="xw-btn" :class="[Number(item.status.pay) === 1 ? 'xw-WBlueB' : 'xw-GBlue']" @click="getAuditFun(4, item, 'pay')">已付款</div>
              <div class="xw-btn" :class="[Number(item.status.ship) === 1 ? 'xw-WBlueB' : 'xw-GBlue']" @click="getAuditFun(4, item, 'ship')">已发货</div>
              <div class="xw-btn" :class="[Number(item.status.receive) === 1 ? 'xw-WBlueB' : 'xw-GBlue']" @click="getAuditFun(4, item, 'receive')">已签收</div>
              <div class="xw-btn" :class="[Number(item.status.invoice) === 1 ? 'xw-WBlueB' : 'xw-GBlue']" @click="getAuditFun(4, item, 'invoice')">已开票</div>
              <div class="xw-btn" :class="[Number(item.status.void) === 1 ? 'xw-WBlueB' : 'xw-GBlue']" @click="getAuditFun(4, item, 'void')">已作废</div>
            </div>
            <div class="LTT-con xw-flex xw-flex-align">
              <div class="xw-flex-W1 xw-color-13">时间：{{item.date}}</div>
              <div class="LTT-can xw-act xw-flex xw-flex-align" @click="getAuditFun(2, item)" v-if="!item.isSign && Number(item.signImg.length) === 0"><em class="fa fa-edit"></em>修改</div>
              <div class="LTT-can xw-act xw-flex xw-flex-align" @click="getAuditFun(5, item)"><em class="fa fa-plus"></em>复制新增</div>
            </div>
          </li>
        </ul>
      </div>
    </div>
    <layer-view ref="layer"/>
    <layer-view ref="layerBox"/>
  </div>
</template>

<style scoped>
/* ---- */
.list-tract li { padding: 0 1rem; overflow: hidden; }
.list-tract li:before { left: 1rem; right: 1rem; }
.list-tract li:nth-of-type(1):before { display: none; }
.LTT-title { padding: 1.6rem 0 0; line-height: 2.5rem; font-size: 1.7rem; font-weight: bold; }
.LTT-btns { padding: 1rem 0; }
.LTT-btns .xw-btn { padding: 0.6rem 0.5rem; }
.LTT-con { padding: 0 0 1.6rem; }
.LTT-can { margin: 0 0 0 1.2rem; }
.LTT-can em { margin-right: 0.5rem; color: #aaaaaa; }
</style>
